/*
 * @Author: lp
 * @Date: 2022-01-17 19:14:53
 * @LastEditTime: 2022-06-25 16:48:57
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @Description: 标签页仓库模块
 * @FilePath: //nien-vue3-admin//src//store//modules//setting.ts
 */
import { defineStore } from 'pinia'
import { setViewStorage, getViewStorage, getCacheStorage } from "@/utils/tagCaches"

const useTagsView = defineStore('tagsView', {
  state: () => ({ 
    visitedViews: getViewStorage(),
    cachedViews: getCacheStorage(),
  }),
  actions: {
    addVisitedView(v) {
      if (this.visitedViews.some(item => item.path == v.path)) return
      this.visitedViews.push(
        { ...v, title: v.meta.title || 'no-name' },
      )
      setViewStorage(this.visitedViews)
     },
    addCachedView(v) {
      if (this.cachedViews.includes(v.name)) return
      if (!v.meta.noCache) {
        this.cachedViews.push(v.name)
      }
    },
    addView(v) {
      this.addCachedView(v)
      this.addVisitedView(v)
    },
    delVisitedView(v) {
      for (const [i, item] of this.visitedViews.entries()) {
        if (item.path == v.path) {
          this.visitedViews.splice(i, 1)
          break
        }
      }
      setViewStorage(this.visitedViews)
    },
    delCachedView(v) {
      const index = this.cachedViews.indexOf(v.name)
      index > -1 && this.cachedViews.splice(index, 1)
      return Promise.resolve()
    },
    delView(v) {
      this.delVisitedView(v)
      this.delCachedView(v)
      return Promise.resolve()
    },
    delOthersVisitedViews(v) {
      this.visitedViews = this.visitedViews.filter(
        item => item.meta.affix || item.path == v.path,
      )
    },
    delOthersCachedViews(v) {
      const index = this.cachedViews.indexOf(v.name)
      if (index > -1) {
        this.cachedViews = this.cachedViews.slice(index, index + 1)
      } else {
        this.cachedViews = []
      }
    },
    delOthersViews(v) {
      this.delOthersVisitedViews(v)
      this.delOthersCachedViews(v)
      return Promise.resolve()
    },
    delAllVisitedViews() {
      this.visitedViews = this.visitedViews.filter(tag => tag.meta.affix)
    },
    delAllCachedViews() {
      this.cachedViews = []
    },
    delAllViews() {
      this.delAllVisitedViews()
      this.delAllCachedViews()
      return Promise.resolve()
    },
    updateVisitedView(v) {
      for (let item of this.visitedViews) {
        if (item.path === v.path) {
          item = Object.assign(item, v)
          break
        }
      }
      setViewStorage(this.visitedViews)
    }, 
  },
})
export default useTagsView
